package com.qumitech.visualnovel.component.config;

import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.databind.introspect.AnnotatedField;
import com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition;
import com.google.common.base.Optional;
import io.micrometer.core.instrument.util.StringUtils;
import org.springframework.stereotype.Component;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.schema.ModelPropertyBuilderPlugin;
import springfox.documentation.spi.schema.contexts.ModelPropertyContext;

@Component
public class SwaggerNameAnnotationPlugin implements ModelPropertyBuilderPlugin {

    @Override
    public void apply(ModelPropertyContext context) {

        final Optional<BeanPropertyDefinition> beanPropertyDefinition = context.getBeanPropertyDefinition();
        if (!beanPropertyDefinition.isPresent()) {
            return;
        }

        final AnnotatedField annotatedField = beanPropertyDefinition.get().getField();
        if (annotatedField == null) {
            return;
        }
        final JSONField jsonField = annotatedField.getAnnotation(JSONField.class);
        if (jsonField == null) {
            return;
        }
        final String apiPropertyName = jsonField.name();
        if (StringUtils.isNotBlank(apiPropertyName)) {
            context.getBuilder().name(apiPropertyName);
        }
    }

    @Override
    public boolean supports(DocumentationType documentationType) {
        // 支持所有有的接口文档
        return true;
    }

}
